package com.danskin.wechat.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.danskin.wechat.cache.JedisClient;
import com.danskin.wechat.entity.Menu;
import com.danskin.wechat.entity.RoleInfo;
import com.danskin.wechat.entity.UserInfo;
import com.danskin.wechat.model.AccessResponse;
import com.danskin.wechat.service.MenuService;
import com.danskin.wechat.service.UserService;
import com.danskin.wechat.util.JsonUtils;
import com.danskin.wechat.util.Page;
import com.danskin.wechat.util.RightsHelper;


/**
 * @author hanwei
 */
@Controller
@RequestMapping("user")
public class UserController extends BaseController {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private MenuService menuService;
	
	@Autowired
	private JedisClient jedis;
	
	
	
	/**
	 * 菜单权限处理
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "", method = RequestMethod.GET)
	public String index(HttpServletRequest request,Model model) {
	        try {
	        	UserInfo user = (UserInfo)request.getAttribute("user");
	            //LoginUser user = this.getLoginUser();               //读取session中的用户信息(单独用户信息)
	            if (user != null) {
	            	 String USERNAME = user.getUserName();
	            	 int roleCode = user.getRoleCode();
	            	 List<Menu> allmenuList = new ArrayList<Menu>();
	                if(user.getMpId()>0){
	                	Map<String,Object> conditionMap=new HashMap<String,Object>();
	                	conditionMap.put("menuType", 1);
	                	conditionMap.put("parentId", 0);
	                	conditionMap.put("userName", USERNAME);
	                	allmenuList= menuService.listOperatorMenuByCondtion(conditionMap);
	                	//session.setAttribute(USERNAME + "SESSION_MENU", allmenuList);//菜单权限放入session中
	                	String parameter = request.getParameter("redirectUrl");
	                	if(StringUtils.isNotBlank(parameter)){
	                		if(parameter.equals(request.getRequestURI())){
	                			    if(roleCode<3){
	    	                		model.addAttribute("redirectUrl", "app/dashboard");
	    	                		}else{
	    	                		model.addAttribute("redirectUrl", "user/login_default");
	    	                		}
	                		}else{
	                			model.addAttribute("redirectUrl", parameter);
	                		}
	                		
	                	}else{
	                		if(roleCode<3){
	                		model.addAttribute("redirectUrl", "app/dashboard");
	                		}else{
	                		model.addAttribute("redirectUrl", "user/login_default");
	                		}
	                	}
	                	
	                }else{
	                	Map<String,Object> conditionMap=new HashMap<String,Object>();
	                	conditionMap.put("menuType", 0);
	                	conditionMap.put("parentId", 0);
	                	allmenuList= menuService.listAllMenuByCondtion(conditionMap);
	                 	String parameter = request.getParameter("redirectUrl");
	                	if(StringUtils.isNotBlank(parameter)){
	                		if(parameter.equals(request.getRequestURI())){
	                			model.addAttribute("redirectUrl", "app/list");
	                		}else{
	                			model.addAttribute("redirectUrl", parameter);
	                		}
	                		
	                	}else{
	                		model.addAttribute("redirectUrl", "app/list");
	                	}
	                	
	                	
	                }
	                
	                
	                model.addAttribute("user", userService.getUserByID(user.getId()));
	                model.addAttribute("menuList", allmenuList);
	               
	                return "user/main";
	            } else {
	               return "user/login";//session失效后跳转登录页面
	            }
	        } catch (Exception e) {
	        	logger.error(e.getMessage(), e);
	            return "user/login";
	            
	        }
	}
	@RequestMapping(value = "login_default", method = RequestMethod.GET)
	public String login_default() {
		
		return "user/index";
	}

	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String login(HttpServletRequest request,Model model) {
		String parameter = request.getParameter("redirect");
		model.addAttribute("redirect", parameter);
		return "user/login";
	}


	@RequestMapping(value = "doLogin", method = RequestMethod.POST)
	@ResponseBody
	public AccessResponse doLogin2(String userName, String userPwd,HttpServletRequest request,HttpServletResponse response) {
		 AccessResponse login = userService.userLogin(userName, userPwd, request, response);
		return login ;
	}
	
	
	
    @RequestMapping(value = "/showList", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object getChannelProductsList(Page page) throws Exception {
    	List<UserInfo> list = userService.getAllUser(page);
        return pagelistToJSONForBootStrapTable(list, page);
    }
    @RequestMapping(value = "/toCheckUserName", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String toCheckUserName(String userName) throws Exception {
    	
    	Map<String,Object> map=new HashMap<String, Object>();
    	List<UserInfo> name = userService.queryByUserName(userName);
    	if(name.size()>0){
    		
    		map.put("status", 400);
    		map.put("msg", "用户名重复");
    	}else{
    		map.put("status", 200);
    		map.put("msg", "用户名可用");
    	}
    	return JsonUtils.objectToJson(map);
    }
    
    
    @RequestMapping(value = "/toCheckRoleName", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String toCheckRoleName(String roleName) throws Exception {
    	roleName = new String(roleName.getBytes("iso-8859-1"), "UTF-8");
    	Map<String,Object> map=new HashMap<String, Object>();
    	List<RoleInfo> name = userService.queryByRoleName(roleName);
    	if(name.size()>0){
    		map.put("status", 400);
    		map.put("msg", "用户名重复");
    	}else{
    		map.put("status", 200);
    		map.put("msg", "用户名可用");
    	}
    	return JsonUtils.objectToJson(map);
    }
    
    
    
    
    
    /**
     * 根据角色权限获取本权限的菜单列表(递归处理)
     *
     * @param menuList：传入的总菜单
     * @param roleRights：加密的权限字符串
     * @return
     */
    public List<Menu> readMenu(List<Menu> menuList, String roleRights) {
        for (int i = 0; i < menuList.size(); i++) {
            menuList.get(i).setHasMenu(RightsHelper.testRights(roleRights, menuList.get(i).getId()));
            if (menuList.get(i).isHasMenu()) {        //判断是否有此菜单权限
                this.readMenu(menuList.get(i).getSubMenu(), roleRights);//是：继续排查其子菜单
            } else {
                menuList.remove(i);
                i--;
            }
        }
        return menuList;
    }
    
    
}
